package com.zhj.rabbitmq.transaction;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @program: rabbimmq-demo
 * @description: 事务消息，消息接收
 * @author: zhengjibin
 * @create: 2020-11-18 13:59
 * @Version 1.0
 **/
public class TransactionReceiveMessage {

    public static void main(String[] args) throws IOException, TimeoutException {

        ConnectionFactory factory = new ConnectionFactory();
        //配置rabbitmq的链接信息
        factory.setHost("122.112.198.94");
        factory.setPort(5672);
        factory.setUsername("admin");
        factory.setPassword("admin");
        Connection connection = null;// 定义rabbitmq的网络连接 ，一个连接
        Channel channel = null;//定义一个链接中的通道
        connection = factory.newConnection();//通过工厂获得连接
        channel = connection.createChannel();//通过连接获得通道
        String queueName = "transaction_queue";
        String exchangeName = "transaction_exchange";
        String routingkey = "transactionRoutingKey";
        channel.queueDeclare(queueName,true,false,false,null);//这段代码可以不用，只有确定队列存在，或者在生成端创建
        channel.exchangeDeclare(exchangeName,"direct",true);//这段代码可以不用，只有确定队列存在，或者在生成端创建
        channel.queueBind(queueName,exchangeName,routingkey);//这段代码可以不用，只有确定队列存在，或者在生成端创建
        /**
         * 消费者 是查询数据，所以事务的开启关闭，对消息队列不影响
         * 暂时不会有影响，特殊情况下也会有影响
         */
        channel.txSelect();
        channel.basicConsume(queueName, true, "", new DefaultConsumer(channel) {
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws
                    IOException {
                //super.handleDelivery(consumerTag, envelope, properties, body);
                String message = new String(body, "UTF-8");
                System.out.println(message);
            }
        });
    }

}

